package cn.stylefeng.guns.sys.modular.system.controller;

import cn.hutool.core.util.ZipUtil;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.properties.GzhConfig;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyDoubleCardMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyContractParam;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyDoubleCardParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyDoubleCardResult;
import cn.stylefeng.guns.sys.modular.system.service.*;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 双证审核控制器
 *
 * @author liuy
 * @Date 2022-06-02 11:30:02
 */
@Controller
@RequestMapping("/btyDoubleCard")
public class BtyDoubleCardController extends BaseController {

    private String PREFIX = "/modular/system/btyDoubleCard";

    @Autowired
    private BtyDoubleCardService btyDoubleCardService;
    @Resource
    private WeChatSendTempMsgService weChatSendTempMsgService;
    @Resource
    private BtySzglService  szglService;
    @Resource
    private BtyWmtxlService wmtxlService;
    @Resource
    private BtyDoubleCardMapper cardMapper;
    @Resource
    private GzhConfig gzhConfig;

    // 跳转URL
    private String path = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=";
    private String type = "&response_type=code";
    private String scope = "&scope=snsapi_userinfo";
    private String state = "&state=STATE#wechat_redirect";

    /**
     * 跳转到主页面
     *
     * @author liuy
     * @Date 2022-06-02
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/btyDoubleCard.html";
    }

    /**
     * 新增页面
     *
     * @author liuy
     * @Date 2022-06-02
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/btyDoubleCard_add.html";
    }

    /**
     * 编辑页面
     *
     * @author liuy
     * @Date 2022-06-02
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/btyDoubleCard_edit.html";
    }

    /**
     * 新增接口
     *
     * @author liuy
     * @Date 2022-06-02
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(BtyDoubleCardParam btyDoubleCardParam) {
        this.btyDoubleCardService.add(btyDoubleCardParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author liuy
     * @Date 2022-06-02
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(BtyDoubleCardParam btyDoubleCardParam) {
        this.btyDoubleCardService.update(btyDoubleCardParam);
        return ResponseData.success();
    }

    /**
     * 修改工程营业执照等信息同步到双证审核
     * @param param
     * @return
     */
    @RequestMapping("/updateTaskStatus")
    @ResponseBody
    public ResponseData updateTaskStatus(BtyDoubleCardParam param) {
        int proId=param.getProId();
        BtyDoubleCard card=btyDoubleCardService.getOne(new QueryWrapper<BtyDoubleCard>().eq("pro_id",proId));
        if(ToolUtil.isNotEmpty(card)){
           int status=card.getStatus();
            if(status==4|status==1|status==2|status==3){
                List<BtyDoubleCardResult>list=cardMapper.taskList(proId);
                if(ToolUtil.isNotEmpty(list)&&list.size()>0){
                    for (BtyDoubleCardResult taskResult : list) {
                        int taskId=taskResult.getTaskId();
                        //营业执照图片
                        if(taskId==11){
                            card.setBusinessLicensePic(taskResult.getContent());
                        }
                        //营业执照名称
                        if(taskId==56){
                            card.setBusinessLicense(taskResult.getContent());
                        }
                        //统一社会信用代码
                        if(taskId==57){
                            card.setSocialCreditCode(taskResult.getContent());
                        }
                        //营业执照地址
                        if(taskId==55){
                            card.setBusinessLicenseAddress(taskResult.getContent());
                        }
                        //法人姓名
                        if(taskId==47){
                            card.setFrxm(taskResult.getContent());
                        }
                        //法人身份证
                        if(taskId==42){
                            card.setFrsfz(taskResult.getContent());
                        }
                        //卫生许可证
                        if(taskId==13){
                            card.setFoodBusinessLicensePic(taskResult.getContent());
                        }
                        //卫生许可证年审日期
                        if(taskId==44){
                            card.setFoodBusinessLicenseDate(taskResult.getContent());
                        }
                        if(ToolUtil.isNotEmpty(card.getBusinessLicensePic())&&ToolUtil.isNotEmpty(card.getFoodBusinessLicensePic())&&ToolUtil.isNotEmpty(card.getFrsfz())){
                            card.setStatus(2);
                        }else if(status==4){
                            card.setStatus(2);
                        }else{
                            card.setStatus(1);
                        }
                    }
                }

                card.setRejectReason("");
                card.setCreateTime(new Date());
                btyDoubleCardService.updateById(card);
            }
        }
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author liuy
     * @Date 2022-06-02
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(BtyDoubleCardParam btyDoubleCardParam) {
        this.btyDoubleCardService.delete(btyDoubleCardParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author liuy
     * @Date 2022-06-02
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(BtyDoubleCardParam btyDoubleCardParam) {
        BtyDoubleCard detail = this.btyDoubleCardService.getById(btyDoubleCardParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author liuy
     * @Date 2022-06-02
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(BtyDoubleCardParam btyDoubleCardParam) {
        return this.btyDoubleCardService.findPageBySpec(btyDoubleCardParam);
    }

    /**
     *营运经理列表
     * @return
     */
    @ResponseBody
    @RequestMapping("/yyjlList")
    public List<Map> yyjlList(){
        List<Map> list=btyDoubleCardService.yyjlList();
        return list;
    }

    /**
     *根据营运经理获取督导列表
     * @return
     */
    @ResponseBody
    @RequestMapping("/ddList")
    public List<Map> ddList(String yyjl){
        List<Map> list=btyDoubleCardService.ddList(yyjl);
        return list;
    }

    /**
     * 单店催办
     * @param btyDoubleCardParam
     * @return
     */
    @RequestMapping("/cuiBan")
    @ResponseBody
    public ResponseData cuiBan(BtyDoubleCardParam btyDoubleCardParam) {
        List<BtyDoubleCardResult>list=btyDoubleCardService.openidList(btyDoubleCardParam.getId());
        if(ToolUtil.isNotEmpty(list)&&list.size()>0){
            String dm=list.get(0).getGcdm();
            String openid=list.get(0).getOpenid();
            Integer proId=list.get(0).getProId();
            Long userId=list.get(0).getUserId();
            String title="催办提醒";
            String data = "双证负责人满文洁提醒您,"+dm+"请尽快完成上传营业执照及卫生许可证等信息;";
            JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, title, title, DateUtil.getNow(), data);
            String[] openids = new String[]{openid};
            //String[] openids = new String[]{"o6zZi6P9T27EDCVodqUtiSQ7ryiI","o6zZi6B7U-0eHP6L4wgMudy0ZSJU","o6zZi6EDPlVpLmRQSWijwhSI8wmM","o6zZi6KsRlOu2-qjB3J7yNw2E8Lg"};
            //public static final String BDURL= ConstantsContext.getGZHUrl() + "?action=/gongcheng/ustask&client=wechatOfficial";
            String wsUrl = BusConst.BDURL + "&proId="+proId+ "&userId="+userId;
            String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(wsUrl) + type + scope + state;
            //String url = path +"wx0d04611c4cc1cc65"+ "&redirect_uri=" + URLEncoder.encode(wsUrl) + type + scope + state;
            System.out.println("url:"+url);
            weChatSendTempMsgService.sendmsg(openids, url, tempObj);
        }
        return ResponseData.success();
    }

    /**
     * 多店催办
     * @return
     */
    @RequestMapping("/cuiBanAll")
    @ResponseBody
    public ResponseData cuiBanAll() {
        List<BtyDoubleCardResult>list=btyDoubleCardService.msgList();
        if(ToolUtil.isNotEmpty(list)&&list.size()>0){
            for (BtyDoubleCardResult result : list) {
                String dm=result.getGcdm();
                String openid=result.getOpenid();
                String title="催办提醒";
                String data = "双证负责人满文洁提醒您,"+dm+"请尽快完成上传营业执照及卫生许可证等信息;";
                JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, title, title, DateUtil.getNow(), data);
                String[] openids = new String[]{openid};
                //String[] openids = new String[]{"o6zZi6P9T27EDCVodqUtiSQ7ryiI","o6zZi6B7U-0eHP6L4wgMudy0ZSJU"};
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
            }
        }
        return ResponseData.success();
    }

    /**
     * 驳回
     * @param btyDoubleCardParam
     * @return
     */
    @RequestMapping("/reject")
    @ResponseBody
    public ResponseData reject(BtyDoubleCardParam btyDoubleCardParam) {
        BtyDoubleCard card=btyDoubleCardService.getById(btyDoubleCardParam.getId());
        if(ToolUtil.isNotEmpty(card)){
            card.setStatus(4);
            card.setRejectReason(btyDoubleCardParam.getRejectReason());
            card.setOperateTime(new Date());
            btyDoubleCardService.updateById(card);
        }
        List<BtyDoubleCardResult>list=btyDoubleCardService.openidList(btyDoubleCardParam.getId());
        if(ToolUtil.isNotEmpty(list)&&list.size()>0){
            String dm=list.get(0).getGcdm();
            String openid=list.get(0).getOpenid();
            String reason=list.get(0).getRejectReason();
            Integer proId=list.get(0).getProId();
            Long userId=list.get(0).getUserId();
            String title="催办提醒";
            String data = "【"+dm+"】双证被驳回，请重新上传，驳回原因："+reason+"";
            JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, title, title, DateUtil.getNow(), data);
            String[] openids = new String[]{openid};
            //String[] openids = new String[]{"o6zZi6P9T27EDCVodqUtiSQ7ryiI","o6zZi6B7U-0eHP6L4wgMudy0ZSJU","o6zZi6EDPlVpLmRQSWijwhSI8wmM","o6zZi6KsRlOu2-qjB3J7yNw2E8Lg"};
            //双证审核url
            //User user = btyWxMapper.selectUser(dd); 营业执照taskId=11  卫生许可证taskId=13
            //String wsUrl = BusConst.SZSHURL + "&proId="+proId+ "&taskId=13" + "&userId=1478215364882403330";
            String wsUrl = BusConst.SZSHURL + "&proId="+proId+ "&userId="+userId;
            String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(wsUrl) + type + scope + state;
            //String url = path +"wx0d04611c4cc1cc65"+ "&redirect_uri=" + URLEncoder.encode(wsUrl) + type + scope + state;
           // System.out.println("url:"+url);
            weChatSendTempMsgService.sendmsg(openids, url, tempObj);
        }
        return ResponseData.success();
    }

    /**
     * 通过
     * @param btyDoubleCardParam
     * @return
     */
    @RequestMapping("/pass")
    @ResponseBody
    public ResponseData pass(BtyDoubleCardParam btyDoubleCardParam) {
        BtyDoubleCard card=btyDoubleCardService.getById(btyDoubleCardParam.getId());
        if(ToolUtil.isNotEmpty(card)){
            card.setStatus(3);
            card.setOperateTime(new Date());
            btyDoubleCardService.updateById(card);
            //通过后的门店双证信息需同步到双证管理中 天财店名，妖码，工程店名，工程地址，营运经理，法人姓名，法人身份证，美团店名，饿了么店名，
            // 食品经营许可证图片，食品经营许可证截止日期，营业执照图片，营业执照名称，统一社会信用代码，营业执照地址
            BtySzgl szgl=szglService.getOne(new QueryWrapper<BtySzgl>().eq("yaoma",card.getYaoma()));
            if(ToolUtil.isNotEmpty(szgl)){
              if(ToolUtil.isNotEmpty(card.getYyjl())){
                  szgl.setYyjl(card.getYyjl());
              }
                if(ToolUtil.isNotEmpty(card.getFrxm())){
                    szgl.setYyzzfr(card.getFrxm());
                }

                if(ToolUtil.isNotEmpty(card.getFrsfz())){
                    szgl.setFrCard(card.getFrsfz());
                }
                if(ToolUtil.isNotEmpty(card.getFoodBusinessLicensePic())){
                    szgl.setSpjyxkz(card.getFoodBusinessLicensePic());
                }
                if(ToolUtil.isNotEmpty(card.getFoodBusinessLicenseDate())){
                    szgl.setSpjyxkzrq(card.getFoodBusinessLicenseDate());
                }
                if(ToolUtil.isNotEmpty(card.getBusinessLicensePic())){
                    szgl.setYyzz(card.getBusinessLicensePic());
                }
                if(ToolUtil.isNotEmpty(card.getBusinessLicense())){
                    szgl.setYyzzmc(card.getBusinessLicense());
                }
                if(ToolUtil.isNotEmpty(card.getBusinessLicenseAddress())){
                    szgl.setYyzzdz(card.getBusinessLicenseAddress());
                }
                if(ToolUtil.isNotEmpty(card.getSocialCreditCode())){
                    szgl.setShxydm(card.getSocialCreditCode());
                }

                BtyWmtxl wmtxl=wmtxlService.getOne(new QueryWrapper<BtyWmtxl>().eq("yaoma",card.getYaoma()));
                if(ToolUtil.isNotEmpty(wmtxl)){
                    if(ToolUtil.isNotEmpty(wmtxl.getMt())){
                      szgl.setMt(wmtxl.getMt());
                    }
                    if(ToolUtil.isNotEmpty(wmtxl.getElm())){
                        szgl.setElm(wmtxl.getElm());
                    }
                }
                szglService.updateById(szgl);
            }


        }

        return ResponseData.success();
    }

    /**
     * 被驳回列表
     * @return
     */
    @RequestMapping("/rejectList")
    @ResponseBody
    public LayuiPageInfo rejectList() {
        return btyDoubleCardService.findPageReject();
    }

    /**
     * 已提交列表
     * @return
     */
    @RequestMapping("/submitList")
    @ResponseBody
    public LayuiPageInfo submitList() {
        return btyDoubleCardService.findPageSubmit();
    }

    /**
     * 驳回原因
     * @return
     */
    @RequestMapping("/rejectReason")
    @ResponseBody
    public ResponseData rejectReason(BtyDoubleCardParam param) {
        //List<BtyDoubleCard>list=btyDoubleCardService.list(new QueryWrapper<BtyDoubleCard>().eq("pro_id",param.getProId()));
        BtyDoubleCard card=btyDoubleCardService.getOne(new QueryWrapper<BtyDoubleCard>().eq("pro_id",param.getProId()));
        return ResponseData.success(card);
    }

    /**
     * 导出excel
     * @param request
     * @param response
     * @param param
     * @return
     */
    @RequestMapping("/export")
    public ResponseEntity<byte[]> export(HttpServletRequest request, HttpServletResponse response, BtyDoubleCardParam param) {
        return this.btyDoubleCardService.exportMx(request, response, param);
    }

    /**
     * 批量下载图片
     */
    @RequestMapping(value = "/btnDown")
    @ResponseBody
    public Object btnDown(@RequestParam("ids") String ids, HttpServletRequest request, HttpServletResponse response){
        this.btyDoubleCardService.btnDown(ids,request,response);

        String urls="D:/szsh/sztp/";
        ZipUtil.zip(urls);
        return SUCCESS_TIP;
    }

}


